package ac.beiwo.baas.object.dao;

import com.mongodb.DB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.stereotype.Component;

import java.util.Hashtable;
import java.util.Map;

@Component
public class MongoDao {

    private MongoDbFactory mongo;
    private Map<String, DB> dbMap;

    @Autowired
    public MongoDao(MongoDbFactory mongo) {
        this.mongo = mongo;
        dbMap = new Hashtable<>();
    }

    public DB db(String appId) {
        String name = getDbName(appId);
        DB db = dbMap.get(name);
        if (db == null) {
            db = mongo.getDb(name);
            dbMap.put(name, db);
        }
        return db;
    }

    private String getDbName(String appId) {
        return "baas" + "_" + appId;
    }


}